import { useEffect, useState } from 'react';
import { Card, Table, Image } from 'antd';
import { getOrderDetail } from '../../services/order';
import { useParams } from '@umijs/max'
import type { Order } from './index'

const { Column } = Table;

type Goods = {
  goodsCount: number;
  goodsCoverImg: string;
  goodsId: string;
  goodsName: string;
  sellingPrice: number;
}

const prefix = (url: string) => {
  if (url && url.startsWith('http')) {
    return url;
  } else {
    return `http://localhost:8080${url}`;
  }
};

const OrderDetail = () => {
  const [data, setData] = useState<Order>();
  const [tableData, setTableData] = useState<Goods[]>([]);
  const { id } = useParams();

  useEffect(() => {
    getOrderDetail(id as string).then(res => {
      setData(res.data);
      setTableData(res.data.ecomOrderItemVOS);
    })
      .catch(error => {
        console.error(error);
      });
  }, [id]);

  return (
    <Card>
      <div style={{ display: 'flex', justifyContent: 'space-around' }}>
        <Card className="data-item" hoverable>
          <div className="card-header">
            <span>订单状态</span>
          </div>
          <div>
            {data?.orderStatusString}
          </div>
        </Card>
        <Card className="data-item" hoverable>
          <div className="card-header">
            <span>创建时间</span>
          </div>
          <div>
            {data?.createTime}
          </div>
        </Card>
        <Card className="data-item" hoverable>
          <div className="card-header">
            <span>订单号</span>
          </div>
          <div>
            {data?.orderNo}
          </div>
        </Card>
      </div>
      <Table dataSource={tableData} style={{ width: '100%', marginTop: 20 }}>
        <Column
          title="商品图片"
          dataIndex="goodsCoverImg"
          key="goodsCoverImg"
          render={(_, record: Goods) => (
            <Image style={{ width: '100px' }} src={prefix(record?.goodsCoverImg)} alt="商品主图" />
          )}
        />
        <Column title="商品编号" dataIndex="goodsId" key="goodsId" />
        <Column title="商品名" dataIndex="goodsName" key="goodsName" />
        <Column title="商品数量" dataIndex="goodsCount" key="goodsCount" />
        <Column title="价格" dataIndex="sellingPrice" key="sellingPrice" />
      </Table>
    </Card>
  );
};

export default OrderDetail;
